import React, { createRef } from "react";
import { ViewProps } from "react-native/Libraries/Components/View/ViewPropTypes";
import { Dimensions, Image, ScrollView, StyleSheet, View } from "react-native";
import { CmsItemModel } from "../../Page/Main/UserCenter/Data";


export interface BannerProps extends ViewProps {
  bannerData: Array<CmsItemModel>;
}

class BannerView extends React.Component<BannerProps> {

  private readonly bannerWidth: number = 0;
  private currentIndex: number = 0;
  private scrollViewRef = createRef<ScrollView>();

  private intervalId?: NodeJS.Timeout;

  constructor(props: BannerProps) {
    super(props);
    this.bannerWidth = this.getBannerWidth();
  }

  getBannerWidth(): number {
    const screenWidth = Dimensions.get("window").width;
    const marginHorizontal = 16 * 2;
    const paddingHorizontal = 4 * 2;
    return (screenWidth - marginHorizontal - paddingHorizontal) / 2;
  }

  pageBanner() {
    const maxIndex = this.props.bannerData.length - 2;
    if (this.currentIndex < 0 || this.currentIndex > maxIndex) {
      this.currentIndex = 0;
    }
    const scrollX = this.bannerWidth * this.currentIndex;
    const position = { x: scrollX, y: 0, animated: true };
    this.scrollViewRef.current?.scrollTo(position);
  }

  componentDidMount() {
    this.intervalId = setInterval(() => {
      this.currentIndex++;
      this.pageBanner();
    }, 1000);
  }

  componentDidUpdate(prevProps: Readonly<BannerProps>, prevState: Readonly<{}>, snapshot?: any) {
    this.currentIndex = 0;
  }

  componentWillUnmount() {
    clearInterval(this.intervalId);
  }

  render() {
    console.log(`bannerWidth=${this.bannerWidth}`);
    const banner = this.props.bannerData.map((cmsItem, index) => {
      return <View key={index} style={{ width: this.bannerWidth }}>
        <Image style={BannerStyle.banner_image}
               source={{ uri: cmsItem.resourceUrl }} />
      </View>;
    });

    return <View style={BannerStyle.banner}>
      <ScrollView
        ref={this.scrollViewRef}
        showsHorizontalScrollIndicator={false}
        showsVerticalScrollIndicator={false}
        horizontal={true}
        style={BannerStyle.scrollView}>
        {banner}
      </ScrollView>
    </View>;
  }
}

const BannerStyle = StyleSheet.create({
  scrollView: {
    marginHorizontal: 4,
    marginVertical: 12,
    flex: 1
  },
  banner: {
    backgroundColor: "white",
    borderRadius: 8,
    marginHorizontal: 16,
    marginTop: 8
  },
  banner_image: { marginHorizontal: 4, flex: 1, height: 56, borderRadius: 4 }
});


export default BannerView;
